<?php

namespace app\admin\controller;

use app\CommonController;
use app\exception\CommonException;
use app\plugins\upload\WebUploader;
use app\service\FileService;


class Upload extends CommonController
{

    public function __construct(FileService $service)
    {
        parent::__construct();
        $this->service = $service;
    }


    public function index()
    {
        $post = $this->request->post();
        if (empty($post["current_num"])) {
            throw new CommonException("缺少当前分片数");
        }
        if (empty($post["total_num"])) {
            throw new CommonException("缺少分片总数");
        }
        if (empty($post["uuid"])) {
            throw new CommonException("随机id");
        }
        $file = $this->request->file("file");
        if (empty($file)) {
            throw new CommonException("请选择文件");
        }
        $ext = $file->getOriginalExtension();
        $webUploader = new WebUploader();
        $webUploader->setNumber($post["current_num"])
            ->setTotalNumber($post["total_num"])
            ->setFileId($post["uuid"])
            ->setTopic($ext)
            ->init()
            ->putFile(file_get_contents($file->getPathname()));
        $state = $webUploader->getState();
        $data = ["code" => 0, "msg" => "上传成功", "state" => $state];
        if ($state) {
            $data["url"] = $webUploader->getRealPath();
            $arr["type"] = $post["file_type"];
            $arr["ext"] = $ext;
            $arr["name"] = $file->getOriginalName();
            $arr["hash"] = hash_file('md5', $webUploader->getAbsolutePath());
            $arr["url"] = $data["url"];
            $arr["mime"] = $webUploader->getMimeType();
            $arr["size"] = $post["size"];
            $arr["status"] = 1;
            $arr["uid"] = session("uid");
            $arr["module"] = app('http')->getName();
            $this->service->save($arr);
        }
        return json($data);
    }
}